/**
 * menu
 * 菜单
 */
function menu() {
    var cookieKey = 'mid',
        mid = parseInt(cookie(cookieKey), 10) || 11,
        $mainMenu = $('#mainNav ul'),
        $mainMenuNode = $mainMenu.find('li a'),
        $subMenu = $('#subNav');

    $mainMenuNode.click(function(){
        $mainMenuNode.removeClass('selected');
        $(this).addClass('selected');
        mid = $(this).attr('mid');
        cookie(cookieKey, mid);
        $subMenu.find('dl').hide();
        $subMenu.find('dl[mid=' + mid + ']').show();
    })

    if(isNaN(mid) || mid < 10) {
        $firstMenu = $mainMenu.find('li:first-child a');
        mid = $firstMenu.attr('mid');
    }

    $mainMenu.find('li a[mid=' + mid + ']').trigger('click');
}

function spliter() {
    var cookieKey = 'spliter',
        cssClass = 'navOff',
        s = cookie(cookieKey),    //表示当前显示状态，0表示隐藏，1表示显示
        $spliter = $('#spliter'),
        $main = $('#main'),
        s2 = s == null || s == '0' ? 1 : 0; //重置显示状态值

    $spliter.click(function(){
        var s = parseInt(cookie(cookieKey), 10),
            s2 = s ? 0 : 1,
            action = s2 ? 'addClass' : 'removeClass'; 

        $main[action](cssClass);
        cookie(cookieKey, s2);

        $(window).trigger('SPLITER_CLICK', {d : s2});
    })

    cookie(cookieKey, s2);
    //$spliter.trigger('click');
}

function searchMore() {
    var cookieKey = 'searchMore',
        $searchMore = $('.btnSearchMore'),
        s = cookie(cookieKey),
        $searchMoreItem = $('[rel=searchMoreItem]'),
        action, s2;

    $searchMore.click(function() {
        var s = parseInt(cookie(cookieKey), 10),
            s2 = s ? 0 : 1,
            action = s2 ? 'show' : 'hide';

        $searchMoreItem[action]();
        cookie(cookieKey, s2);
    })

    if(s == null || s == '0') {
        $searchMoreItem.hide();
        s2 = false;
    } else {
        cookie(cookieKey, 0);
        $searchMore.trigger('click');
        s2 = true;
    }

    $searchMore.attr('checked', s2);
}


/**
 * search
 * 执行查询
 *
 * @return void
 */
function search() {
    /**
     * 绑定查询按钮事件 
     */
    $('.btnSearch').unbind('click').click(function(){
        var $form = $(this).parents('form'),
            url = $form.attr('action');
            param = $form.serialize(),
            $searchItem = $form.find('[name^=search_item_val_]');  //有多个查询项目但中只能查询一项的条目,与之对应的值在search_item_中

        /**
         * 多个查询项目合并到一起，只能选一项进行查询的情况
         */
        if($searchItem.length > 0) {
            $.each($searchItem, function(k, v){
                var $o = $(v),
                    name = $o.attr('name'),
                    index = name.split('_')[3];

                if(index.length < 1) {
                    return false;
                }

                var $name2 = $form.find('[name=search_item_' + index + ']'),
                    name2 = $name2.val();

                if(typeof(name2) == 'undefined') {
                    return false;
                }

                param += '&' + name2 + '=' + $o.val();
            })
        }

        url += url.indexOf('?') == -1 ? '?' : '&';
        url += param;

        window.location.href = url;
    });

    /**
     * 绑定回车键至查询按钮
     */
    $(window).on('keydown', function(e) {
        if(e.keyCode == '13') {
            $('.btnSearch').trigger('click');   //这样做可能有问题，比如页面中有多个.btnSearch查询按钮时。目前大部分页面中只有一个查询按钮，所以这样用
        }
    });

    /**
     * 清空查询表单
     */
    $('.btnResetForm').click(function(){
        $form = $(this).parents('form');
        $form[0].reset();

        $form.find("input[class*='datebox-f']").each(function(v){
            $(this).datebox('setValue', '');
        });
    });

    /**
     * 回填查询数据至查询表单 
     */
    var searchDao = Conf.get('searchDao');

    if(typeof(searchDao) == 'object') {
        new Form($('#formSearch'), new Model(searchDao));
    }
}

/**
 * sort2
 * 列表中按指定的字段排序
 *
 * @return void
 */
function sort2() {
    var $item = $('a[sort]'),
        $formSearch = $('#formSearch');

    if($formSearch.length < 1) {
        return false;
    }

    $item.click(function(){
        $formSearch.find('[name=sort]').val($(this).attr('sort'));
        $formSearch.find('[name=sortdir]').val($(this).attr('sortdir') || 'DESC');
        $formSearch.find('.btnSearch').trigger('click');
    })

    var sort = $formSearch.find('[name=sort]').val(),
        sortdir = $formSearch.find('[name=sortdir]').val(),
        newSortdir = sortdir.toUpperCase() == 'DESC' ? 'ASC' : 'DESC';

    $item.filter('[sort="' + sort + '"]').attr('sortdir', newSortdir);
}


/**
 * del
 * 删除单条数据确认
 *
 * @return void
 */
function del() {
    $('a[rel=del]').click(function(){
        if(!confirm('确认删除吗？')) {
            return false;
        }

        var url = $(this).attr('href'),
            gotoUrl = $(this).attr('goto') || '',   //跳转地址，用于删除成功后跳转到此地址
            progress = $.messager.progress;

        progress({text : '正在删除数据，请稍等...'});

        $(this).removeAttr('href');

        $.getJSON(url, function(d){
            progress('close');

            if(!d.s) {
                alert(d.m);

                return false;
            }

            if(d.s) {
                reload(gotoUrl);
            }
        })
    });
}

/**
 * fixThead
 * 固定表头
 * 此只对#zoneBodyContent中第一个table.table2且含有thead的表格起作用
 *
 * @return void
 */

function fixThead() {
    var $zoneBodyContent = $('#zoneBodyContent'),
        $table = $zoneBodyContent.find('table.table2');

    if($table.length < 1) {
        return false;
    }

    var fixTheadHtml = '<div id="fixTheadZone" style="display:none;">'
                        + '<table class="table2" style="position:fixed;top:30px;"></table>'
                        + '</div>',
        $fixTheadZone = $(fixTheadHtml);

    $zoneBodyContent.prepend($fixTheadZone);

    $thead = $table.eq(0).find('thead');

    if($thead < 1 || ($thead.find('th').length < 1)) {
        return false;
    }
        
    var $zoneBody = $('#zoneBody'),
        $zoneBodySearch = $('#zoneBodySearch'),
        fixTheadZoneView = 0; //0表示隐藏，1表示显示

    var cloneTheadHandler = function() {
            var $thead2 = $thead.clone(true),
                $thead2Th = $thead2.find('th'),
                $theadTh = $thead.find('th');

            $.each($theadTh, function(k, v){
                $thead2Th.eq(k).width($(v).width());
            })

            $fixTheadZone.find('table').html($thead2).width($table.eq(0).width());
            $fixTheadZone.show();
        };

    $('#zoneBody').scroll(function(e) {
        var scrollTop = $(this).scrollTop(),
            scrollLeft = $(this).scrollLeft();

        if($zoneBodySearch.height() + 10 - scrollTop > 0) {
            if(fixTheadZoneView) {
                $fixTheadZone.hide();
                fixTheadZoneView = 0;
            }

            return true;
        }

        var marginLeft = 0;

        if(scrollLeft > 0) {
            marginLeft = -scrollLeft;
        }

        $fixTheadZone.find('table').css('margin-left', marginLeft);

        if(!fixTheadZoneView) {
            cloneTheadHandler();
            fixTheadZoneView = 1;
        }
    });

    $(window).bind('SPLITER_CLICK', function() {
        if(fixTheadZoneView) {
            cloneTheadHandler();
        }
    })
}

/**
 * checkboxChoice
 * 复选框选择列表
 *
 * 如果指定了$parent,那么就只在$parent范围内查找所有节点
 *
 * @return void
 */
var CheckboxChoice = function($parent) {
    this.$parent = $parent || null;
    this.masterTag = 'checkboxChoiceMasterDom';
    this.$master = $('input[t=' + this.masterTag + ']', this.$parent);
    this.itemTag = this.$master.attr('item') || 'checkboxChoiceItemDom';
}

CheckboxChoice.prototype.init = function(){
    if(this.$master.length < 1) {
        return false;
    }

    var that = this;

    this.$master.unbind('click').click(function() {
        var $item = $('input[t=' + that.itemTag + ']', that.$parent),
            status = $(this).attr('checked') ? true : false;

        $item.attr('checked', status);
    });
}

CheckboxChoice.prototype.getChoiceLength = function() {
    var $item = $('input[t=' + this.itemTag + ']:checked', this.$parent);

    return $item.length;
}

function initDateBox() {
    $('[t=datebox]').pikaday({
        i18n: {
            previousMonth : '上月',
            nextMonth     : '下月',
            months        : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
            weekdays      : ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
            weekdaysShort : ['日','一','二','三','四','五','六']
        },
        format: 'YYYY-MM-DD'
    });
}

$(function(){
    menu();
    spliter();
    searchMore();
    search();
    sort2();
    del();
    fixThead();
    firm();

    initDateBox();

    (function() {
        var a = new CheckboxChoice;
        a.init();
    })()
})

